package org.crown.project.api;


import lombok.extern.slf4j.Slf4j;
import org.crown.common.jwt.JwtTokenUtil;
import org.crown.project.api.config.constant.SysConst;
import org.crown.project.api.module.wechatuser.domain.TbWechatUser;
import org.crown.project.api.module.wechatuser.service.TbWechatUserService;
import org.crown.project.api.utils.UserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author wufengsheng
 */
@Slf4j
@RestController
public abstract class BaseApi {

    @Autowired
    protected UserUtil userUtil;

    @Autowired
    protected JwtTokenUtil jwtTokenUtil;

    /**
     * API接口前缀
     */
    public static final String API_PATH_PREFIX = "/api/mini/";

    /**
     * 获取API接口前缀
     * @return
     */
    public static String getApiPathPrefix() {
        return BaseApi.API_PATH_PREFIX;
    }

    /**
     * 创建token
     *
     * @return
     */
    protected synchronized String createToken(String userName, Long userId) {
        String randomKey = jwtTokenUtil.getRandomKey();
        String token = jwtTokenUtil.generateToken(userName, randomKey, userId);
        return token;
    }

    /**
     * 创建token
     *
     * @return
     */
    protected synchronized String createToken(String userName, Long userId, String openId) {
        String randomKey = jwtTokenUtil.getRandomKey();
        String token = jwtTokenUtil.generateToken(userName, randomKey, userId, openId);
        return token;
    }

    /**
     * 获取当前微信userId
     *
     * @return
     */
    protected synchronized Long getUserId() {
        return userUtil.getUserId();
    }

    /**
     * 获取当前微信openid
     *
     * @return
     */
    protected synchronized String getOpenId() {
        return userUtil.getOpenId();
    }

    @Autowired
    private TbWechatUserService tbWechatUserService;

    /**
     * 获取当前微信用户
     *
     * @return
     */
    protected synchronized TbWechatUser getTbWechatUser() {
        Long userId = userUtil.getUserId();
        if (userId != null) {
            return tbWechatUserService.getById(userId);
        }
        return null;
    }

}
